package com.pinoc.demo.config.zk;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.ZooKeeperServer;

import java.util.concurrent.CountDownLatch;

/**
 * @author yinpeng
 */
public class ZookeeperInitBySessionPwd implements Watcher {
	public static CountDownLatch connectedSemaphore = new CountDownLatch(1);
	public static void main(String[] args) {
		try {
			ZooKeeper zooKeeper = new ZooKeeper("localhost:2181", 5000, new ZookeeperInitBySessionPwd());
			System.out.println(zooKeeper.getState());
 			connectedSemaphore.await();
			long sessionId = zooKeeper.getSessionId();
			System.out.println("session: " + sessionId);
			byte[] sessionPasswd = zooKeeper.getSessionPasswd();
			//使用session 和pwd
			zooKeeper = new ZooKeeper("localhost:2181", 5000, new ZookeeperConfig(), 1L, "tst".getBytes());
			zooKeeper = new ZooKeeper("localhost:2181", 5000, new ZookeeperConfig(), sessionId, sessionPasswd);
			Thread.sleep(Integer.MAX_VALUE);
		} catch (Exception e) {
			System.out.println("zookeeper session established");
		}
	}
	@Override
	public void process(WatchedEvent watchedEvent) {
		System.out.println("watch event: " + watchedEvent);
		if(KeeperState.SyncConnected == watchedEvent.getState()) {
			connectedSemaphore.countDown();
		}
	}
}
